<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="1100px"
      draggable
      :align-center="true"
      @close="closeDialog"
      destroy-on-close
      style="min-width: 1100px"
      class="maxhDialog"
    >
      <div class="search-container">
        <el-form :model="searchParam" :inline="true">
          <el-form-item label="采集时间">
            <el-date-picker
              v-model="searchParam.collectionTimeSearch"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="getcollectionTime"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchChange"
              ><i-ep-search />搜索</el-button
            >
            <el-button @click="handleReset"><i-ep-refresh />重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-card shadow="never" class="table-container">
        <el-table
          ref="dataTableRef"
          v-loading="loading"
          :data="tableData"
          highlight-current-row
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            label="采集时间"
            prop="collectionTime"
            min-width="120"
            align="center"
            show-overflow-tooltip
          />
          <el-table-column
            label="设备编号"
            prop="deviceCode"
            min-width="120"
            align="center"
            show-overflow-tooltip
          />
          <el-table-column
            label="采集数据"
            min-width="300"
            prop="dataText"
            show-overflow-tooltip
          />
          <el-table-column
            fixed="right"
            label="操作"
            width="120"
            align="center"
          >
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                link
                @click="openDialogdetail(scope.row)"
              >
                <i-ep-edit />
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          :background="true"
          :current-page="pageable.pageNum"
          :page-size="pageable.pageSize"
          :page-sizes="[10, 25, 50, 100]"
          :total="pageable.total"
          layout="total, sizes, prev, pager, next, jumper"
          class="mt-[20px]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>

      <iotdevicedata-edit
        :visible="addDialog.visible"
        :title="addDialog.title"
        :data="addDialog.data"
        @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
        :is-readonly="addDialog.readvisible"
        @change-visible="changeVisible"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import dayjs from "dayjs";

defineOptions({
  name: "EQUOPERATINGPARAMETERSDETAIL",
  inheritAttrs: false,
});

const dictionaryStore = useDictStoreHook();

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  assetType: {
    type: Number,
    default: 1,
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

watch(
  () => props.data,
  (newVal: any) => {
    if (newVal.id) {
      searchParam.value = {
        ...searchParam.value,
        deviceCode: newVal.equipCode || "",
        // assetType: props.assetType,
        paramType: newVal.paramType || "",
      };
      getTableList();
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

// 请求参数
const requestApi = "/iotadmin/deviceData/queryHistoryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 获取当前时间，number为空是当前时间，number为向前推几分钟
function getNowTime(num?: number) {
  // 创建一个 Date 对象
  var today = new Date();
  if (num) {
    today.setMinutes(today.getMinutes() + num);
  }

  // 获取年、月、日、时、分、秒
  let year = today.getFullYear();
  let month = today.getMonth() + 1; // 月份是从 0 开始计数的，需要加1
  let day = today.getDate();
  let hours = today.getHours();
  let minutes = today.getMinutes();
  let seconds = today.getSeconds();

  // 格式化输出
  let formattedTime =
    year +
    "-" +
    (month < 10 ? "0" : "") +
    month +
    "-" +
    (day < 10 ? "0" : "") +
    day +
    " " +
    (hours < 10 ? "0" : "") +
    hours +
    ":" +
    (minutes < 10 ? "0" : "") +
    minutes +
    ":" +
    (seconds < 10 ? "0" : "") +
    seconds;

  return formattedTime;
}

const getTimeStart = () => {
  const now = new Date();
  let midnight = dayjs(
    new Date(now.getFullYear(), now.getMonth(), now.getDate())
  ).format("YYYY-MM-DD HH:mm:ss");
  return midnight;
};
// 初始化搜索参数数据
const searchParamInit = {
  collectionTimeSearch: [getTimeStart(), getNowTime()],
  startTime: getTimeStart(),
  endTime: getNowTime(),
  deviceTypeCode: "",
  deviceCode: props.data.equipCode || "",
  // assetType: props.assetType,
  paramType: props.data.paramType || "",
};
// getTimeStart()
const deleteParam = {
  api: "/iotadmin/iotdevicedata/delete",
  data: {},
};
let isSameDay = ref(false);
// 点击搜索进行时间判断
const searchChange = () => {
  // 判断是否选择设备编号
  if (!searchParam.value.deviceCode) {
    ElMessage.warning("请选择设备编号！");
    return;
  }
  // 判断是否选择时间以及 是否是同一天
  if (!searchParam.value.collectionTimeSearch) {
    ElMessage.warning("请选择时间！");
  } else if (
    !searchParam.value.collectionTimeSearch[0] &&
    !searchParam.value.collectionTimeSearch[1]
  ) {
    ElMessage.warning("请选择时间！");
  } else {
    const start = dayjs(searchParam.value.collectionTimeSearch[0]);
    const end = dayjs(searchParam.value.collectionTimeSearch[1]);
    isSameDay.value = start.isSame(end, "day");
    if (isSameDay.value) {
      search();
    } else {
      ElMessage.warning("请选择同一天时间！");
    }
  }
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(row: any) {
  const { data } = await request({
    url: `/iotadmin/deviceData/get/${row.deviceCode}/${row.id}`,
    method: "get",
  });
  addDialog.data = data;
}

/** 打开设备采集数据表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "设备采集数据详情";
  getInfo(roleObj);
  addDialog.readvisible = true;
  addDialog.visible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

function getcollectionTime(data: any) {
  if (data) {
    searchParam.value.startTime = data[0] ?? "";
    searchParam.value.endTime = data[1] ?? "";
  } else {
    searchParam.value.startTime = "";
    searchParam.value.endTime = "";
  }
}

// 重置搜索框
const handleReset = () => {
  searchParam.value.collectionTimeSearch = [getTimeStart(), getNowTime()];
  searchParam.value.startTime = getTimeStart();
  searchParam.value.endTime = getNowTime();
  searchParam.value.deviceTypeCode = "";
  searchParam.value.deviceCode = props.data.equipCode;
  // searchParam.value.assetType = props.assetType;
  searchParam.value.paramType = props.data.paramType;
  search();
};
</script>
<style lang="scss" scoped>
:deep(.maxhDialog .el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto;
  padding: 20px;
  .el-scrollbar {
    max-height: calc(70vh - 265px);
    overflow-y: auto;
  }
}
:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  width: 120px;
}
:deep(.el-descriptions__content.el-descriptions__cell.is-bordered-content) {
  min-width: 180px;
}
</style>
